class User < ActiveRecord::Base
  attr_accessor :password
  attr_protected :id, :salt
  
  # these fields are required to create a user
  validates_presence_of :first_name, :last_name, :email, :phone, :addr1, :city, :state, :zip
  validates_uniqueness_of :email
  validates_format_of :email,	:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,	:message => "Invalid email"

  validates_presence_of :password, :on => :create
  validates_confirmation_of :password

  before_save :encrypt_password

  has_many :orders, :dependent => :destroy

  # authenticate a user
  def self.authenticate(email, password)
    user = find_by_email(email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end

  # encrypt the password
  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
  
  # show if the user is validated
  def validate?
		update_attribute('validated', true)
		if self.validated
		  return true
		else
		  return false
		end
  end

  # sends a new password to a user (forgot password)
#  def send_new_password
#    new_pass = User.random_string(10)
#    self.password = self.password_confirmation = new_pass
#    self.save
#    UserMailer.deliver_forgot_password(self.email, self.login, new_pass)
#  end

  # generate a random string for a password
  def self.random_string(len)
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    return newpass
  end
end
